package cn.action.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import cn.action.BaseAction;
import cn.beans.Administrator;
import cn.beans.DownloadFile;
import cn.utils.PageModel;

@SuppressWarnings("unchecked")
public class DownloadAction extends BaseAction {

	private File file;
	private String fileFileName;
	private String fileContentType;
	private PageModel pm = new PageModel();
	private int currentPage;
	private int pageSize;
	private String fileId;
	private String keywords;
	private String param;
	
	/**
	 * 上传文件
	 */
	public void uploadFile() {
		String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
		String sadminName = (String)ActionContext.getContext().getSession().get("adminName");
		if(null == sadminId){
			sadminId = param;
			if(null != sadminId){
				Administrator a = commonservice.findById(sadminId, new Administrator());
				sadminName = a.getName();
			}
		}
		try {
			if (null == sadminId || "".equals(sadminId.trim()) || "null".equals(sadminId.trim())) {
				Exception e = new Exception();
				throw e;
			} else {

				if (file != null) {
					String uuid = UUID.randomUUID().toString();
					InputStream is = new FileInputStream(file);
					int pos = fileFileName.lastIndexOf(".");
					String extName = fileFileName.substring(pos).toLowerCase();
					String uploadFilename = uuid + extName;
					String root = ServletActionContext.getServletContext().getRealPath("/upload/files");
					File app = new File(root);
					if (!app.exists()) {
						app.mkdir();
					}
					File dest = new File(root, uploadFilename);

					OutputStream os;
					os = new FileOutputStream(dest);
					byte[] buffer = new byte[1024];
					int len = 0;
					int total = 0;
					while ((len = is.read(buffer)) > 0) {
						total += len;
						os.write(buffer, 0, len);
					}
					is.close();
					os.close();

					DownloadFile df = new DownloadFile();
					df.setAdminId(sadminId);
					df.setAdminName(sadminName);
					df.setCreDate(new Date());
					df.setExtent(extName);
					df.setName(fileFileName);
					df.setSaveName(uploadFilename);
					df.setSize(total);
					
					commonservice.saveDemo(df);
					
					this.sendMsgAjax("1", null);

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载文件(入口)
	 * @return
	 */
	public String downloadFile(){
		return SUCCESS;
	}
	
	/**
	 * 下载文件(文件流)
	 * @return
	 */
	public InputStream getIsFile(){
		try{
			DownloadFile df = commonservice.findById(fileId, new DownloadFile());
			fileFileName = df.getName();
			fileFileName = new String(fileFileName.getBytes("GBK"),"ISO8859-1");
			String filePath = "/upload/files/" + df.getSaveName();
			return ServletActionContext.getServletContext().getResourceAsStream(filePath);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 附件删除
	 * 
	 * @throws Exception
	 */
	public void deleteFile() throws Exception {
		try{
			String[] ids = fileId.split(",");
			int length = ids.length;
			for(int i=0; i<length; i++){
				DownloadFile df = commonservice.findById(ids[i], new DownloadFile());
				String root = ServletActionContext.getServletContext().getRealPath("/upload/files");
				String filePath = root + "\\" + "\\" + df.getSaveName(); 
				File f = new File(filePath);
				
				commonservice.deleteDemo(df, null);
				
				if(f.exists()){
					f.delete();
				}
			}
			
			this.sendMsgAjax("success", null);
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 文件列表
	 * @return
	 */
	public String listFile(){
		
		pm.setCurrentPage(currentPage);
		pm.setPageSize(pageSize);
		
		List listOne = new ArrayList();
		String[] propertyName = { "name" };
		String[] propertyCon = { "like" };
		Object[] propertyValue = { keywords };
		String[] condition = null;
		listOne.add(propertyName);
		listOne.add(propertyCon);
		listOne.add(propertyValue);
		listOne.add(condition);
		
		String[] orderPropertyName = { "creDate" };
		String[] orderValue = { "DESC" };
		
		pm = commonservice.findDataByPage(pm, "DownloadFile", listOne, null, null, null, null, null, null, orderPropertyName, orderValue);
		
		return SUCCESS;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public PageModel getPm() {
		return pm;
	}

	public void setPm(PageModel pm) {
		this.pm = pm;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}
	
	public String getParam() {
		return param;
	}
	
	public void setParam(String param) {
		this.param = param;
	}
	
}
